/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-07-25 10:33:04
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2024-07-25 17:44:29
 * @FilePath: /vue3-uniapp/src/utils/pipeFns/time.ts
 */
import { type Observable, delayWhen, of, delay } from 'rxjs';
import dayjs from 'dayjs';

/**
 * 以创建时间为标准，每隔interval毫秒时间发布一次
 * @param interval 发布的时间间隔，单位毫秒
 * @param immediate 是否立即发布
 * @returns pipeable函数
 */
export const createDelayPublish = (interval: number, immediate = true) => {
    let time = Date.now();
    let isFirst = true;
    return () =>
        <T>(source: Observable<T>) => {
            return source.pipe(
                delayWhen((opt) => {
                    const now = Date.now();
                    const diff = now - time;
                    if (!isFirst && diff <= interval) {
                        time += interval;
                        return of(opt).pipe(delay(dayjs(time).toDate()));
                    }
                    isFirst = false;
                    if (immediate) {
                        time = now;
                        return of(opt);
                    } else {
                        time += interval;
                        return of(opt).pipe(delay(dayjs(time).toDate()));
                    }
                })
            );
        };
};
